<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>非父子组件间传值（Bus/总线/发布订阅模式/观察者模式）</title>
  <script src="../asset/js/vue.js"></script>
</head>

<body>
  <div id="root">
    <child content='Xu'></child>
    <child content='Qi'></child>
  </div>
  <script>
    Vue.prototype.bus = new Vue()
    Vue.component('child', {
      data() {
        return {
          selfContent: this.content
        }
      },
      props: {
        content: String
      },
      template: `<div @click='handleClick'>{{selfContent}}</div>`,
      methods: {
        handleClick() {
          // console.log(this.content)
          /* $emit 方法并传入事件的名字，来向父级组件触发一个事件 */
          this.bus.$emit('change', this.selfContent)
        }
      },
      mounted() {
        var this_ = this;
        /* 用 v-on 在博文组件上监听这个事件，就像监听一个原生 DOM 事件一样 */
        this.bus.$on('change', function (msg) {
          console.log('mounted:', msg)
          this_.selfContent = msg
        })
      }
    })
    let vm = new Vue({
      el: '#root',
    })
  </script>
</body>

</html>